<?php

/**
 * This is a singleton class that interacts with the database
 *
 * @author Tony
 */
include '../users/User.php';
class DataHandler {
  private static $instance;
  private $con;

  private function __construct() {
    $con = mysql_connect("localhost", "ttony21_Tony", "cse308");
    if (!$con) {
      die('Could not connect: ' . mysql_error());
    }
    mysql_select_db("ttony21_GARS", $con);
  }

  public static function singleton() {
    if (!isset(self::$instance)) {
      $className = __CLASS__;
      self::$instance = new $className;
    }
    return self::$instance;
  }

  public function __clone() {
    trigger_error('Clone is not allowed.', E_USER_ERROR);
  }

  public function __wakeup() {
    trigger_error('Unserializing is not allowed.', E_USER_ERROR);
  }
  /*
   * Gets the active user
   */
  public function getActiveUser() {
    return $this->active_user;
  }
  /**
   * Writes a set of records to a database table
   * @param array $records
   * @param string $table_name 
   */
  public function writeToDB($records, $table_name) {
    //Add records to database    
    $record = current($records);
    while ($record) {
      $sql = "INSERT            
      INTO " . $table_name .            
      " VALUES (";
      $data = current($record);
      while ($data) {
        $sql .= "'$data'";
        $data = next($record);
        if ($data) {
          $sql .= ",";
        }
      }
      $sql .= ");";
      echo "$sql<br><br>";
      mysql_query($sql);
      $record = next($records);
    }
  }

  /**
   * Authenticates user credentials
   * @param string $name
   * @param string $password
   * @return bool 
   */
  public function authenticate($name, $password) {
    $sql = "SELECT * 
            FROM users 
            WHERE username = '$name' 
            AND password = '" . md5($password) . "'";
    $result = mysql_query($sql);
    if ($row = mysql_fetch_array($result)) {
      //Successful login
      $username = $row['username'];
      $num_assigned_reviews = $row['num_assigned_reviews'];
      $workload = $row['workload'];
      $email = $row['email'];
      $countries = $row['countries'];
      $fields = $row['fields'];
      $role = $row['role'];
      $available = $row['available'];
      $active_user = new User($num_assigned_reviews, $workload, $username, $email, 
          $countries, $fields, $role, $available);
      //Set session vars
      $_SESSION['role'] = $role;
      $_SESSION['name'] = $username;
      return true;
    } else {
      //Failed login
      echo '<label class = "error">Invalid username or password</label>';
      return false;
    }
  }

  /**
   * Prints a table from the database
   * @param string $table_name 
   */
  function printTable($table_name) {
    $sql = "SELECT * FROM " . $table_name;
    //Print fields
    $result = mysql_query($sql);
    $fields = array();
    echo "<table class = 'appTable' id = '$table_name'>
          <thead>
          <tr>";
    while ($property = mysql_fetch_field($result)) {
      $field_name = $property->name;
      array_push($fields, $field_name);
      echo "<th scope = 'col'>$field_name</th>";
    }
    echo "</tr>
          </thead><tfoot></tfoot>";
    //Print records
    echo '<tbody>';
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
      foreach ($fields as $field_name) {
        $data = $row[$field_name];
        $data = trim($data, "\"");
        echo "<td>" . $data . "</td>";
      }
      reset($fields);
      echo "</tr>";
    }
    echo '</tbody></table>';
  }

  /**
   * Adds user to database
   */
  private function addUser($name, $password) {
    $sql = "INSERT 
            INTO users (username, password, role) 
            VALUES ('$name', '" . md5($password) . "', 'CHAIR');";
    mysql_query($sql);
  }

  /**
   * Creates new Users table
   */
  private function createTables()
  {

    //$sql = A_STRING_CONTAINING_A_CREATE_STATEMENT
  
    //mysql_query($sql);
    //
    
  }

}

?>
